package com.example.april2.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean matchRoot = new AntPathMatcher().match("/april2/", requestURI);
        boolean matchLogin = new AntPathMatcher().match("/april2/login", requestURI);
        if (matchRoot || matchLogin){
            return true;
        }

        String userId = (String)request.getSession().getAttribute("id");
        if (userId == null || StringUtils.isBlank(userId)){
            response.sendRedirect("http://localhost:8090/april2/");
            return false;
        }else{
            return true;
        }
    }
}
